var hexMD5 = require('./md5.js').hexMD5

var getId =  function (len, timestamp) {
  len = len || 32
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length
  var pwd = ''
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
// 全局参数
var d = {
  id: "",
  encrypt: "md5",
  sign: "",
  client: { caller: "wechat" },
  data: {},
  timestamp: new Date().getTime(),
  format: "json"
}
// 随机数
d.id = getId(10)
// md5加密
var beforeSign = d.id + ':' + "846d2cb0c7f09c3ae802c42169a6302b" + ":" + d.timestamp
var sign = hexMD5(beforeSign)
d.sign = sign
console.log('公用参数', d)
/**
 * 最终上传到cos的URL
 * 把以下字段配置成自己的cos相关信息，详情可看API文档 https://www.qcloud.com/document/product/436/6066
 * REGION: cos上传的地区
 * APPID: 账号的appid
 * BUCKET_NAME: cos bucket的名字
 * DIR_NAME: 上传的文件目录
 */

var myFolderName = function () {
  var now = new Date();
  var nowYear = now.getFullYear();
  var nowMonth = now.getMonth() + 1;
  if (nowMonth < 10) {
    nowMonth = '0' + nowMonth;
  } else {
    nowMonth = String(nowMonth);
  }
  return '/image/' + nowYear + '-' + nowMonth + '/'
  //    return '/image/' + nowYear + '-' + "05" + '/'
};
var REGION = 'gz'
var BUCKET_NAME =  'webstatic'
var APPID =  '1252911372'
var DIR_NAME = myFolderName()    

var cosUrl = "https://" + REGION + ".file.myqcloud.com/files/v2/" + APPID + "/" + BUCKET_NAME + DIR_NAME
console.log(cosUrl)
/**
 * 上传方法
 * filePath: 上传的文件路径
 * fileName： 上传到cos后的文件名
 */
function upload(filePath, fileName, callback) {
  var getFileName = function (){
    var guid = "";
    for (var i = 1; i <= 32; i++) {
      var n = Math.floor(Math.random() * 16.0).toString(16);
      guid += n;
      if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
        guid += "-";
    }
    return guid;
  } 
  var  fileName = getFileName() + '.jpg'
  // 鉴权获取签名
  wx.request({
    //填写自己的鉴权服务器地址
    url: 'https://m.youyinian.cn/v1/common/cos-sign',
    method: 'POST',
    data: d ,
    success: function (cosRes) {
      console.log(cosRes)
      // 签名
      var signature = cosRes.data.data.periodSign
      //setTimeout(function(){
        // 头部带上签名，上传文件至COS
        wx.uploadFile({
          url: cosUrl + '/' + fileName + '?sign=' + signature,
          filePath: filePath,
          header: {
            'Authorization': signature
          },
          name: 'filecontent',
          formData: {
            op: 'upload'
          },
          success: function (uploadRes) {
            var data = uploadRes.data
            console.log('uploadRes', uploadRes)
            if (uploadRes.statusCode == 403 ){
              upload(filePath, fileName, callback)
              return 
            }
            var imgData = JSON.parse(data)
            var imgUrl = imgData.data.resource_path.split('/webstatic')[1]
            callback && callback(imgUrl)
            console.log(imgData)
            //do something
          },
          fail: function (e) {
            console.log('e', e)
          }
        })
      //},200)
      
    }
  })
}


module.exports  = upload